package scriptEngine

import (
	"errors"
	"fmt"
	"gitee.com/fierce_wolf/go-fox-edge-common/commConfig"
	"gitee.com/fierce_wolf/go-fox-edge-common/commLogger"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"sync"
)

type scriptEngineLoader struct {
	topicMap sync.Map
}

func (e *scriptEngineLoader) initialized() (err error) {
	// 定义一个最终的异常拦截，用来防止可能的代码BUG
	defer func() {
		if r := recover(); r != nil {
			message := fmt.Sprintf("scriptLoader.initialized()捕获到异常:%v", r)
			commLogger.Console.Error(message)
			err = errors.New(message)
		}
	}()

	serverConfig, err := commConfig.GetConfigParam("serverConfig")
	if err != nil {
		return err
	}

	handler := Map.GetSlice(serverConfig, "handler", make([]interface{}, 0))
	for _, val := range handler {
		data := val.(map[string]interface{})

		// 取出topic的uplink
		topic := Map.GetMap(data, "topic", make(map[string]interface{}))
		uplink := Map.GetString(topic, "uplink", "")
		if uplink == "" {
			continue
		}

		// 构造相关的脚本引擎
		scripts := Map.GetSlice(data, "script", make([]interface{}, 0))
		operationKeys := service.buildScriptEngine(scripts)

		// 保存双方的关系
		subscribe.save(uplink, operationKeys)
	}

	return nil
}
